package com.kaixinff.kaixin001.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

import com.kaixinff.kaixin001.servlet.LoginServlet;
import com.kaixinff.name.NameUtil;
import com.kaixinff.name.User;
import com.kaixinff.net.HttpClient;

public class KXUtil {
	public static final String CHARSET = "UTF-8";
	public static final String REG_URL = "http://reg.kaixin001.com/";
	public static final String LOGIN_URL = "http://login.kaixin001.com";
	public static final String HOST_URL = "http://www.kaixin001.com";
	public static final String XW_URL = "http://www.kaixin001.com/!spiderman";
	public static final String SETTING_FILE = "setting.properties";
	public static HttpClient client;
	public static Proxy GLOBAL_PROXY;
	
	private static String USERS_FILE;
	private static String mainUserEmail;
	private static String mainUserUid;
	private static String password;
	private static Properties uid2Email;
	
	static {
		try {
			InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(SETTING_FILE);
			Properties p = new Properties();
			p.load(in);
			
			USERS_FILE = p.getProperty("users");
			String proxy = p.getProperty("proxy");
			if ("true".equals(proxy)) {
				String host = p.getProperty("proxy.host");
				int port = Integer.parseInt(p.getProperty("proxy.port"));
				GLOBAL_PROXY =  new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
			}
			client = new HttpClient(GLOBAL_PROXY);
			mainUserEmail = p.getProperty("mainUserEmail");
			mainUserUid = p.getProperty("mainUserID");
			password = p.getProperty("password");
			
			uid2Email = new Properties();
			InputStream fin = ClassLoader.getSystemClassLoader().getResourceAsStream("uid2email.properties");
			uid2Email.load(fin);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static String getPassword() {
		return password;
	}
	
	public static String getMainUserEmail() {
		return mainUserEmail;
	}
	
	public static String getMainUserUid() {
		return mainUserUid;
	}
	
	public static Properties getUid2Email() throws IOException {
		return uid2Email;
	}
	
	public static void saveUid2Email() throws IOException {
		if (uid2Email != null) {
			FileOutputStream out = null;
			try {
				out = new FileOutputStream("uid2email.properties");
				uid2Email.store(out, "");
			} finally {
				if (out != null) {
					out.close();
				}
			}
		}
	}
	
	public static String getEmail(String uid) throws IOException {
		return getUid2Email().getProperty(uid);
	}
	
	public static List<User> getUsers(Filter f, HttpServletResponse resp) throws IOException {
		List<User> allUsers = getUsers();
		List<User> users = new ArrayList<User>();
		List<String> emails = new ArrayList<String>();
		for (User user: allUsers) {
			if (f == null || f.access(user)) {
				KXClient client = KXClient.getInstance(user.getId());
				if (!client.isLogined()) {
					emails.add(user.getId());
				}
				users.add(user);
			}
		}
		if (emails.size() > 0) {
			LoginServlet.initPage(emails, resp);
			return null;
		}
		return users;
	}
	
	public static URI getFileURI(String filename) {
		URL url = ClassLoader.getSystemClassLoader().getResource(filename);
		if (url == null) {
			url = ClassLoader.getSystemClassLoader().getResource(SETTING_FILE);
			return new File(new File(url.getPath()).getParent(), filename).toURI();
		}
		URI uri = null;
		try {
			uri = url.toURI();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		return uri;
	}
	
	public static List<User> getUsers() throws IOException {
		return NameUtil.loadUsers(getFileURI(USERS_FILE));
	}
	
	public static void saveUsers(List<User> users) throws IOException {
		NameUtil.saveUsers(getFileURI(USERS_FILE), users);
	}
	
	public static Map<String, User> getUserMap() throws IOException {
		List<User> users = getUsers();
		Map<String, User> userMap = new HashMap<String, User>();
		for (User user: users) {
			userMap.put(user.getId(), user);
		}
		return userMap;
	}
	
	public static String toUTF(String cont) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0, n = cont.length(); i < n;) {
			char ch = getChar(cont, i);
			while (ch != 0 && (ch != '\\' || getChar(cont, i + 1) != 'u')) {
				sb.append(ch);
				i++;
				ch = getChar(cont, i);
			}
			if (i < n) {
				String str = "" + cont.charAt(i + 2) + cont.charAt(i + 3) + cont.charAt(i + 4) + cont.charAt(i + 5);
				sb.append((char)Integer.valueOf(str, 16).intValue());
				i += 6;
			}
		}
		return sb.toString();
	}
	
	public static String findMessage(String html) {
		html = html.replaceAll("\n", " ");
		html = html.replaceAll("\r", " ");
		html = html.replaceAll("<br>", " ");
		html = html.replaceAll("&nbsp;", " ");
		html = html.replaceAll("(?s)<script.+?>.+?</script>", "");
		html = html.replaceAll("<.+?>", "");
		html = html.replaceAll("关闭", "");
		return toUTF(html).trim();
	}
	
	private static char getChar(String str, int index) {
		if (index >= str.length()) {
			return 0;
		}
		return str.charAt(index);
	}
	
	public static void waitOneSecond() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
